var datagrid = null,tableTree = null;
$(function() {
	initTree();
	initGrid();
});
function save() {
	var nodes = datagrid.datagrid('getChecked');
	var list = [];
	for(var i=0; i < nodes.length; i++){
		list.push(nodes[i].id);
	}
	var type = baseJs.request("type");
	//判断是哪种数据
	var url = type == "query" ? "moduleAction/batchSaveQuery.html" : "moduleAction/batchSaveField.html";
	$.post(host + url, {ids: list.join(","), moduleId: baseJs.request("moduleId")}, function(data) {
		if (data.status == "ok") {
			baseJs.getOpenWindow().alert(data.msg);
			if (type == "query") {
				baseJs.getOpenWindow().querDataGrid.datagrid('reload');
			} else {
				baseJs.getOpenWindow().fieldDataGrid.datagrid('reload');
			}
			cancel();
		} else {
			alert(data.msg);
		}
	}, "json");
}
function cancel() {
	baseJs.getOpenWindow().dialog.close();
}
var treeNode = null;
function initTree() {
	$.post(host + 'tableAction/getTableList.html', {}, function(data) {
		data = data.rows;
		var nodes = [];
		var map = {};
		for (var i = 0;i < data.length;i ++) {
			map[data[i].id] = {
					id: data[i].id,
					text: data[i].text,
					state: 'close'
				};
			if (map[data[i].parentId] != undefined) {
				if (map[data[i].parentId].children == undefined) {
					map[data[i].parentId].children = [];
				}
				map[data[i].parentId].children.push(map[data[i].id]);
			} else {
				nodes.push(map[data[i].id]);
			}
		}
		tableTree = $('#tableTree').tree({
			data: nodes,
			lines: true,
			onClick: function(node){
				treeNode = node;
				serarchFun();
				$("#addField").attr("disabled", false);
			}
		});
	}, "json");
	$("#tableTree").tabs({});
}
function initGrid() {
	datagrid = $('#datagrid').datagrid({
		url : host + 'tableAction/getFieldList.html',
		fit : true,
		fitColumns : true,
		border : false,
		pagination : false,
		nowrap : false,
		singleSelect: false,
		frozenColumns: [],
		columns : [[
			{field : 'id', title : '字段名', checkbox: true},
			{field : 'name', title : '字段名', width : 60},
			{field : 'text', title : '字段名称', width : 60},
			{field : 'typeId', title : '类型', width : 60},
			{field : 'isId', title : '主键', width : 60,
				formatter: function(value, row, index) {
					return value == 1 ? "是" : "否";
				}
			}
		]],
		toolbar: []
	});
}
function serarchFun() {
	datagrid.datagrid('load',{
		"name" : $("#name").val(),
		"tableId" : treeNode.id
	});
}